package com.lanou.renrenxin.activity;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.easemob.chat.EMChatManager;
import com.lanou.renrenxin.R;
import com.lanou.renrenxin.base.BaseActivity;
import com.lanou.renrenxin.base.BaseApplication;
import com.lanou.renrenxin.custommodule.CircleImageView;
import com.lanou.renrenxin.mybomb.MyUser;
import com.lanou.renrenxin.scanmodel.CreateQRCodeAty;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.datatype.BmobFile;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.UpdateListener;
import cn.bmob.v3.listener.UploadFileListener;

/**
 * Created by dllo on 16/3/21.
 */
public class PersonalActivity extends BaseActivity implements View.OnClickListener {

    private static final int PHOTO_REQUEST_TAKEPHOTO = 1;// 拍照
    private static final int PHOTO_REQUEST_GALLERY = 2;// 从相册中选择
    private static final int PHOTO_REQUEST_CUT = 3;// 结果

    File tempFile = new File(Environment.getExternalStorageDirectory(), getPhotoFileName());

    private TextView textView;
    private CircleImageView headimage;
    private EditText nick, address, sex, regional, chatacterTxt;
    private String path;
    private Button saveBtn;
    private int count = 0;
    private BmobQuery<MyUser> query;
    private Handler handler;
    private List<MyUser> data;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_personal);

        textView = (TextView) findViewById(R.id.tv_activity_personal_userame);
        headimage = (CircleImageView) findViewById(R.id.iv_activity_personal_headimg);
        nick = (EditText) findViewById(R.id.et_activity_personal_nick);
        address = (EditText) findViewById(R.id.et_activity_personal_address);
        sex = (EditText) findViewById(R.id.et_activity_personal_sex);
        regional = (EditText) findViewById(R.id.et_activity_personal_regional);
        chatacterTxt = (EditText) findViewById(R.id.et_activity_personal_chatacterTxt);
        saveBtn = (Button) findViewById(R.id.btn_activity_personal_save);

        nick.setEnabled(false);
        address.setEnabled(false);
        sex.setEnabled(false);
        regional.setEnabled(false);
        chatacterTxt.setEnabled(false);

        headimage.setOnClickListener(this);
        saveBtn.setOnClickListener(this);
        query = new BmobQuery<>();
        loadPersonalData();

        handler = new Handler(new Handler.Callback() {
            @Override
            public boolean handleMessage(Message msg) {
                if (msg.what == 588) {
                    data = (List<MyUser>) msg.obj;
                    for (MyUser user : data) {
                        textView.setText(EMChatManager.getInstance().getCurrentUser());
                        nick.setText(user.getNick());
                        address.setText(user.getAddress());
                        sex.setText(user.getSex());
                        regional.setText(user.getRegional());
                        chatacterTxt.setText(user.getCharactertxt());
                        if (user.getPic() != null) {
                            user.getPic().loadImage(PersonalActivity.this, headimage);
                        } else {
                            headimage.setImageResource(R.mipmap.headimg);
                        }
                    }
                }
                return false;
            }
        });
    }

    //二维码
    public void QrCode(View view) {
        startActivityForResult(new Intent(this, CreateQRCodeAty.class), 0);
    }

    //返回
    public void back(View view) {
        finish();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_activity_personal_headimg:
                showDialog();
                break;
            case R.id.btn_activity_personal_save:
                // TODO: 16/3/23 编辑和保存
                if (count % 2 == 0) {
                    saveBtn.setText("保存");
                    changeEditStatus(true);
                    count++;
                } else {
                    saveBtn.setText("编辑");
                    changeEditStatus(false);
                    saveHeadImage();
                    count++;
                }
                break;
        }
    }


    private void changeEditStatus(boolean enable) {
        if (enable) {
            nick.setEnabled(true);

            address.setEnabled(true);

            sex.setEnabled(true);

            regional.setEnabled(true);

            chatacterTxt.setEnabled(true);
        } else {
            nick.setEnabled(false);
            address.setEnabled(false);
            sex.setEnabled(false);
            regional.setEnabled(false);
            chatacterTxt.setEnabled(false);
        }
    }

    private void saveHeadImage() {
        if (path != null) {
            final BmobFile file = new BmobFile(new File(path));
            if (file != null) {
                file.uploadblock(this, new UploadFileListener() {
                    @Override
                    public void onSuccess() {
                        savePersonal(file);
                    }

                    @Override
                    public void onFailure(int i, String s) {

                    }
                });
            } else {
                savePersonal(file);
            }
        }
    }

    /**
     * 保存个人信息
     */
    private void savePersonal(final BmobFile file) {


        query.addWhereEqualTo("username", EMChatManager.getInstance().getCurrentUser());
        query.findObjects(this, new FindListener<MyUser>() {
            @Override
            public void onSuccess(List<MyUser> list) {
                for (MyUser user : list) {
                    Log.e("PersonalActivity", user.getObjectId());

                    MyUser myUser = new MyUser();
                    myUser.setValue("username", EMChatManager.getInstance().getCurrentUser());
                    if (file != null) {
                        myUser.setValue("pic", file);
                    }
                    myUser.setValue("address", address.getText().toString());
                    myUser.setValue("sex", sex.getText().toString());
                    myUser.setValue("regional", regional.getText().toString());
                    myUser.setValue("charactertxt", chatacterTxt.getText().toString());
                    myUser.update(PersonalActivity.this, user.getObjectId(), new UpdateListener() {
                        @Override
                        public void onSuccess() {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    BaseActivity.ShowToast("保存成功");
                                }
                            });
                        }

                        @Override
                        public void onFailure(int i, String s) {
                            Log.e("≈≈≈≈≈≈≈≈≈", s + "sassas");
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    BaseActivity.ShowToast("保存失败");
                                }
                            });
                        }
                    });
                }
            }

            @Override
            public void onError(int i, String s) {

            }
        });

    }


    private void loadPersonalData() {
        query = new BmobQuery<>();
        query.addWhereEqualTo("username", EMChatManager.getInstance().getCurrentUser());
        query.findObjects(BaseApplication.getContext(), new FindListener<MyUser>() {
            @Override
            public void onSuccess(List<MyUser> list) {
                Message msg = new Message();
                msg.what = 588;
                msg.obj = list;
                handler.sendMessage(msg);
            }

            @Override
            public void onError(int i, String s) {

            }
        });
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // TODO Auto-generated method stub

        switch (requestCode) {
            case PHOTO_REQUEST_TAKEPHOTO:
                startPhotoZoom(Uri.fromFile(tempFile), 150);
                break;

            case PHOTO_REQUEST_GALLERY:
                if (data != null) {
                    startPhotoZoom(data.getData(), 150);
                    Uri uri = data.getData();
                    String[] proj = {MediaStore.Images.Media.DATA};
                    Cursor cursor = managedQuery(uri, proj, null, null, null);
                    //这个是获得用户选择的图片的索引值
                    int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                    cursor.moveToFirst();
                    //最后根据索引值获取图片路径
                    path = cursor.getString(column_index);
                }
                break;

            case PHOTO_REQUEST_CUT:
                if (data != null)
                    setPicToView(data);
                break;
        }
        super.onActivityResult(requestCode, resultCode, data);

    }

    //将进行剪裁后的图片显示到UI界面上
    private void setPicToView(Intent picdata) {
        Bundle bundle = picdata.getExtras();
        if (bundle != null) {
            Bitmap photo = bundle.getParcelable("data");
            headimage.setImageBitmap(photo);
        }
    }

    private void startPhotoZoom(Uri uri, int size) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        // crop为true是设置在开启的intent中设置显示的view可以剪裁
        intent.putExtra("crop", "true");

        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);

        // outputX,outputY 是剪裁图片的宽高
        intent.putExtra("outputX", size);
        intent.putExtra("outputY", size);
        intent.putExtra("return-data", true);

        startActivityForResult(intent, PHOTO_REQUEST_CUT);
    }

    private void showDialog() {
        new AlertDialog.Builder(this)
                .setTitle("头像设置")
                .setPositiveButton("拍照", new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        // TODO Auto-generated method stub
                        dialog.dismiss();
                        // 调用系统的拍照功能
                        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                        // 指定调用相机拍照后照片的储存路径
                        intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(tempFile));
                        startActivityForResult(intent, PHOTO_REQUEST_TAKEPHOTO);
                    }
                })
                .setNegativeButton("相册", new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        // TODO Auto-generated method stub
                        dialog.dismiss();
                        Intent intent = new Intent(Intent.ACTION_PICK, null);
                        intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
                        startActivityForResult(intent, PHOTO_REQUEST_GALLERY);
                    }
                }).show();
    }

    // 使用系统当前日期加以调整作为照片的名称
    private String getPhotoFileName() {
        Date date = new Date(System.currentTimeMillis());
        SimpleDateFormat dateFormat = new SimpleDateFormat("'IMG'_yyyyMMdd_HHmmss");
        return dateFormat.format(date) + ".jpg";
    }
}
